package src.Sixteen;

import cn.hutool.core.io.resource.ResourceUtil;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.util.Hashtable;
import java.util.Vector;

/**
 * @ClassName Question110
 * @Description
 * @Author keke
 * @Time 2022/6/28 21:21
 * @Version 1.0
 */
public class Question110 {

    public static void main(String[] args) {
        ChatServerFrame server = new ChatServerFrame();
        server.createSocket();
    }
}


class ChatServerFrame extends JFrame {

    private static final long serialVersionUID = 7060406254416077287L;
    private JTextArea textAreaInfo;
    private ServerSocket server;
    private Socket socket;
    private Hashtable<String, Socket> map = new Hashtable<>();

    public ChatServerFrame() {
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowIconified(WindowEvent e) {
                setVisible(false);
            }
        });

        setTitle("聊天室服务器");
        setVisible(true);
        setBounds(100, 100, 385, 266);

        JScrollPane scrollPane = new JScrollPane();
        getContentPane().add(scrollPane, BorderLayout.CENTER);

        textAreaInfo = new JTextArea();
        scrollPane.setViewportView(textAreaInfo);

        if (SystemTray.isSupported()) {
            URL resource = getClass().getResource("1.PNG");
            //URL url = ResourceUtil.getResource(, null);
            ImageIcon icon = new ImageIcon(resource);
            Image image = icon.getImage();
            TrayIcon trayIcon = new TrayIcon(image);
            trayIcon.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    if (e.getClickCount() == 2) {
                        showFrame();
                    }
                }
            });
            trayIcon.setToolTip("系统托盘");
            PopupMenu popupMenu = new PopupMenu();
            MenuItem exit = new MenuItem("退出");
            exit.addActionListener(e -> System.exit(0));
            popupMenu.add(exit);
            SystemTray systemTray = SystemTray.getSystemTray();
            try {
                systemTray.add(trayIcon);
            } catch (AWTException e) {
                e.printStackTrace();
            }
        }
    }

    private void showFrame() {
        setVisible(true);
        setState(Frame.NORMAL);
    }

    private class ServerThread extends Thread {
        private Socket socket;

        public ServerThread(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
                while (true) {
                    Vector<?> vector = null;
                    try {
                        vector = (Vector<?>) objectInputStream.readObject();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    if (vector != null && vector.size() > 0) {
                        for (int i = 0; i < vector.size(); i++) {
                            String info = (String) vector.get(i);
                            String key = "";
                            if (info.startsWith("用户：")) {
                                key = info.substring(3);
                                map.put(key, socket);
                                for (String receiveKey : map.keySet()) {
                                    PrintWriter writer = new PrintWriter(map.get(receiveKey).getOutputStream(), true);
                                    for (String receiveKey1 : map.keySet()) {
                                        writer.println(receiveKey1);
                                        writer.flush();
                                    }
                                }
                            } else if (info.startsWith("退出：")) {
                                key = info.substring(3);
                                map.remove(key);
                                for (String receiveKey : map.keySet()) {
                                    PrintWriter writer = new PrintWriter(map.get(receiveKey).getOutputStream(), true);
                                    writer.println("退出：" + key);
                                    writer.flush();
                                }
                            } else {
                                key = info.substring(info.indexOf("：发送给：") + 5, info.indexOf("：的信息是："));
                                String sendUser = info.substring(0, info.indexOf("：发送给："));
                                for (String receiveKey : map.keySet()) {
                                    System.out.println(receiveKey+","+sendUser);
                                    if(sendUser.equals(receiveKey)){
                                        PrintWriter writer = new PrintWriter(map.get(receiveKey).getOutputStream(), true);
                                        writer.println("MSG：" + key);
                                        writer.flush();
                                    }
                                }
                            }
                        }
                    }
                }
            } catch (IOException e) {
                textAreaInfo.append(socket + "已经退出\n");
            }
        }
    }

    public void createSocket() {
        try {
            server = new ServerSocket(9527);
            while (true) {
                textAreaInfo.append("等待新客户连接......\n");
                socket = server.accept();
                textAreaInfo.append("客户端连接成功：" + socket + "\n");
                new ServerThread(socket).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}